package com.example.spider.provider.why10w.persistent;

import cn.hutool.core.io.FileUtil;
import com.example.spider.provider.why10w.Why10wFileNameTemplate;
import com.example.spider.provider.why10w.dto.WhyTaskResult;
import com.example.spider.task.AbstractSpiderTask;
import com.example.spider.util.FileBasedMap;
import lombok.extern.slf4j.Slf4j;
import org.shoulder.core.context.AppInfo;
import org.shoulder.core.exception.CommonErrorCodeEnum;
import org.shoulder.core.util.AssertUtils;
import org.springframework.stereotype.Component;

import java.io.File;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
@Component
public class Why10wRepository extends FileBasedMap<ConcurrentHashMap<String, WhyTaskResult>, String, WhyTaskResult> {

    private Why10wFileNameTemplate why10wFileNameTemplate;

    public Why10wRepository(Why10wFileNameTemplate why10wFileNameTemplate) {
        super(new ConcurrentHashMap<>(), new File(why10wFileNameTemplate.getMergedResultFile()));
        this.why10wFileNameTemplate = why10wFileNameTemplate;
    }

    public void addResult(WhyTaskResult taskResult) {
        AssertUtils.notNull(taskResult.getSource(), CommonErrorCodeEnum.ILLEGAL_PARAM);
        put(taskResult.getUrl(), taskResult);
    }

    public void saveHtml(AbstractSpiderTask<?> task, String html) {
        String htmlFile = task.getIdempotentFilePath();
        FileUtil.writeString(html, htmlFile, AppInfo.charset());
    }

}
